import threading
import time
import datetime
import pymssql
from pymongo import MongoClient



def get_wq_rs():
	conn = pymssql.connect(host = "10.63.2.60", user = "eerpsa", password = "P@ssword", 
		database = "CMAPE")
	rs = None
	try:

		cursor = conn.cursor()
		cursor.execute("SELECT * FROM dbo.T_PROC_WorkQueue WITH(NOLOCK)")
		rs = cursor.fetchall()
		cursor.close()
		# if rs:
		# 	print("count:", len(rs), flush = True)
		# 	for dr in rs:
		# 		print(dr, flush = True)
	except:
		print("catch error")

	conn.close()

	return rs

def check_wq_is_completed(wqid):
	conn = pymssql.connect(host = "10.63.2.60", user = "eerpsa", password = "P@ssword", 
		database = "CMAPE")
	cnt = 0
	try:
		sql = "SELECT COUNT(*) FROM dbo.T_PROC_WorkQueueLog WITH(NOLOCK) WHERE WorkQueueID = %s" % wqid
		
		cursor = conn.cursor()
		cursor.execute(sql)
		cnt = cursor.fetchone()[0]
		# print(cnt)
		cursor.close()

	except Exception as e:
		print("catch error:", e)

	conn.close()

	return cnt > 0

def save_to_mongodb(rs):
	if rs == None:
		return

	m_conn = MongoClient("127.0.0.1", 27017)

	wqquerylog = m_conn.mydb.wqquerylog
	wqquerylog.insert({"create_time": datetime.datetime.now(), "wqcount": len(rs)})

	wqlog = m_conn.mydb.wqlog
	for dr in rs:
		wqid = dr[0]
		item = wqlog.find_one({"wqid":wqid})
		if item:
			# completed = check_wq_is_completed(wqid)
			# print("find exists: completed = ", completed, "wqid = ", wqid)
			wqlog.update({"wqid":wqid}, {"$set":{"updated_time": datetime.datetime.now(), 
				"complted": False}})
		else:
			dic = {"wqid":dr[0], "appid": dr[1], "instid": dr[2], "sn": dr[3], 
				"proname": dr[4], "atyname": dr[5], "nodeid": dr[6],
				"nodename": dr[7], "actname": dr[8], "result": dr[9],
				"oriactioner": dr[10], "curactioner": dr[11], "occdate": dr[12], 
				"xml": dr[13],"create_time": datetime.datetime.now(),
				"updated_time": None,"complted": False}
			wqlog.insert(dic)

	m_conn.close()

def listen_wq():
	rs = get_wq_rs()
	save_to_mongodb(rs)
	print("wq count:", len(rs), flush = True)
		
		

def thread_callback():

	while(True):
		now = datetime.datetime.now()
		print("------ ", now.strftime("%Y-%m-%d %H:%M:%S"), " --------")
		listen_wq()
		print("------ wait 5s to next query --------", flush = True)
		time.sleep(5)
		


t = threading.Thread(target = thread_callback, name = "wq")

t.start()
t.join()



# print_wq_info()
# check_wq_is_completed(70629)


	


